﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using Moonwish.Core;
using Moonwish.Core.DataAccess;
using Moonwish.Core.EntityCore;
using Moonwish.Foundation.DataEntity;

namespace Moonwish.Foundation.DataAccess.SqlServer.ValueObjectClassCmd
{
    public class AddCommand : EntityCommand<V_FDT_ValueObjectClass>
    {
        public AddCommand(DbContext dbContext, List<V_FDT_ValueObjectClass> items, string userId)
            : base(dbContext, items, userId)
        {
        }

        public override void Execute()
        {
            var classSet = DbContext.Set<T_FDT_ValueObjectClass>();
            var ovSet = DbContext.Set<T_FDT_ValueObject>();
            foreach (var item in Items)
            {
                if (item.DataStatus != DataStatus.New.ToString()
                        || item.ChangeTracker.State != ObjectState.Added)
                {
                    throw new InvalidOperationException(String.Format("数据“{0}”不是新增状态，无法添加到数据库。", item.Name));
                }
                var newValueObjectClass = new T_FDT_ValueObjectClass
                {
                    ValueObjectClassId = item.ValueObjectClassId,
                    Code = item.Code,
                    Name = item.Name,
                    OrderNo = item.OrderNo,
                    DataStatus = item.DataStatus,
                    Remark = item.Remark
                };
                foreach (var vo in item.V_FDT_ValueObjects)
                {
                    var newValueObject = new T_FDT_ValueObject
                    {
                        ValueObjectId = vo.ValueObjectId,
                        ValueObjectClassId = vo.ValueObjectClassId,
                        Code = vo.Code,
                        Name = vo.Name,
                        OrderNo = vo.OrderNo,
                        DataStatus = vo.DataStatus
                    };
                    ovSet.Add(newValueObject);
                }
                classSet.Add(newValueObjectClass);
            }
            DbContext.SaveChanges();
        }
    }
}
